<?php
/**
 * Manage Users Records
 *
 * @name manage users records
 * @version		0.7
 * @uses		Zend_Db
 * @package		nats-space
 * @see			http://code.google.com/p/nats-space/
 * @copyright	2008-2010
 * @author		Joseph C. <joseph.cheys@gmail.com>
 */
class Nats4space_Users_Management
{
	/**
	 * Used to enable user
	 */
	const STATUS_ENABLED = 1;

	/**
	 * Used to disable user
	 */
	const STATUS_DISABLED = 0;

	/**
	 * NATS trial membership code
	 */
	const MEMBERSHIP_LEVEL_TRIAL = 1;

	/**
	 * NATS full membership code
	 */
	const MEMBERSHIP_LEVEL_FULL = 0;

	/**
	 * Epoch biller
	 */
	const BILLER_EPOCH = 'EPOCH';

	/**
	 * Netbilling
	 */
	const BILLER_NETBILLING = 'NETBILLING';

	/**
	 * Wts
	 */
    const BILLER_WTS = 'WTS';

    /**
	 * Database instance
	 *
	 * @var Zend_Db_Adapter_Abstract
	 */
	private $_db;

	/**
	 * Constructor
	 *
	 * Assign initial values
	 */
	public function __construct(Zend_Db_Adapter_Abstract $db)
	{
		$this->_db = $db;
	}

	/**
	 * Checks whether the membership level is trial or not
	 *
	 * @param string $memberLogin
	 * @return true if membership level is trial or false otherwise
	 */
	public function isTrial($memberLogin)
	{
	    $sql = 'SELECT trial FROM member WHERE username = ?';

	    if (self::MEMBERSHIP_LEVEL_TRIAL == $this->_db->fetchOne($sql, $memberLogin)) {
	        return true;
	    }

	    return false;
	}

	/**
	 * return biller
	 *
	 * @param string $memberLogin
	 */
	public function getBiller($memberLogin)
	{
	    /**
	     * @todo: check NATS database and return the biller was used to create current member account
         * To get the biller that was used is a multi-step process.
         */

	    // 1)  Get the identid from the member table.
	    $sql = 'SELECT identid FROM member WHERE username = ?';
	    $identId = $this->_db->fetchOne($sql, $memberLogin);

        // 2)  Using the identid look in the identifier table for the billerid.
        $sql = 'SELECT billerid FROM identifier WHERE identid = ?';
	    $billerId = $this->_db->fetchOne($sql, $identId);

        // 3)  Using the billerid look in the biller table to get the actual name of the biller.
        $sql = 'SELECT biller FROM biller WHERE billerid = ?';
        return $this->_db->fetchOne($sql, $billerId);
	}

	/**
	 * Build biller specific upgrade URL
	 * For now only Epoch has unique membership URL all other billers has general upgrade URL
     *
     * @param string $memberLogin member login
     * @param string $linkDomain NATS domain
     * @param int $siteId NATS site ID
     * @param string $epochTiCode Epoch UpgradePlus TI code
     * @return strung biller specific membership upgrade URL
	 */
	public function getUpgradeUrl($memberLogin, $linkDomain, $siteID, $epochTiCode = '')
	{
        $Biller = $this->getBiller($memberLogin);

        switch ($Biller) {

            case self::BILLER_NETBILLING:
                $redirectUrl = 'http://' . $linkDomain . '/signup/upgradeplus.php?site=' . $siteID
                             . '&username=' . $memberLogin;
                break;

            case self::BILLER_EPOCH:
            default:
                $redirectUrl = 'http://' . $linkDomain . '/signup/upgradeplus.php?site=' . $siteID
                             . '&username=' . $memberLogin
                             . '&ti_code=' . $epochTiCode
                             . '&returnurl=' . urlencode('http://' . $linkDomain . '/signup/epoch_upgradeplus_returnurl.php');
                break;

        }

        return $redirectUrl;
	}

    /**
	 * Track login
	 * See details here: http://wiki.toomuchmedia.com/index.php/Nats4_Member_Logging
	 * 
	 * @param string $natsUrl - the url to NATS affiliate tracking system
	 * @param string $userName - members name
	 * @param string $remoteAddr - members remote IP address
	 * @param string $siteIds - coma-separated site IDs mmeber is login to
	 * @return boolean - return true on success open
	 */
	public static function TrackLogin($natsUrl, $userName, $remoteAddr, $siteIds = null)
	{
	    /**
         * Already posted login
         */
   		if (!empty($_SESSION['login_post_ok'])) {
            return;
        }

        /**
         * validate required values to avoid the unpredictable
         * results in NATs membership login statistics
         */
		if (empty($natsUrl)) {
		    throw new Nats4space_Exception('NATS affiliate tracking system URL is empty'); 
		}

		if (empty($userName)) {
			throw new Nats4space_Exception('Members username is empty');
		}
		
		if (empty($remoteAddr)) {
			throw new Nats4space_Exception('Remote IP address is empty');
		}

        /**
         * @todo: validate the $natsUrl to be valid website URL like 'http://www.example.com/'
         */

		// Build redirect URL
		
		// TODO: check for the trailing slash in $natsUrl 
		$redirectUrl = $natsUrl . 'member_loginlog.php';
		
		// Add username
		$redirectUrl .= '?username=' . urlencode($userName);
		
		// Add site ID(s)
		if (null === $siteIds) {
			$redirectUrl .= '&nosite=1';
		} elseif (false === strpos($siteIds, ',')) {
			$redirectUrl .= '&siteid=' . urlencode($siteIds); 
		} else {
			$redirectUrl .= '&siteids=' . urlencode($siteIds);
		}
		
		// Track members remote IP address
		$redirectUrl .= '&ip=' . urlencode($remoteAddr);
		
		// Send the request by opening URL as a file 
		// (check "allow_url_fopen" php.ini directive to enable this)
		// TODO: avoid the dependency to 'allow_url_fopen' directive
		$res = file($redirectUrl);

		// process the result
		if (false !== strpos($res[0], 'FAILURE')) {
		  
			$error_msg = 'Can\'t connect to: ' . $redirectUrl . "\n Error code:" . $res[0] . "\n";
            
			if ('FAILURE: BAD IP' == $res[0]) {
			   $error_msg .= ' To resolve this problem add the following IP addess to your NATS config file: $config[\'SECURE_IPS\'] = array(\'' . $_SERVER['SERVER_ADDR'] . '\'); ';
		       $error_msg .= ' See details here: http://wiki.toomuchmedia.com/index.php/Nats4_Member_Logging';
			}
            
			throw new Nats4space_Exception($error_msg);
		}
        
        /**
         * Save post to session,
         * this will indicate that login informatin is already
         * tracked and there is no any need to process such actions in the future.
         */
        $_SESSION['login_post_ok'] = true;
	}
    
    
    /**
	 * Extracts membership join site
	 *
	 * @param string $memberLogin
	 * @return int site ID
     */
    public function getSite($memberLogin)
    {
	    $sql = 'SELECT siteid FROM member WHERE username = ?';
	    return $siteId = $this->_db->fetchOne($sql, $memberLogin);
    }
}